﻿#ifndef HTTPCLIENT_H
#define HTTPCLIENT_H

#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QByteArray>
#include <QUrl>
#include <QUrlQuery>
#include <QHttpMultiPart>
#include <QHttpPart>
#include <QDebug>
#include <QTimer>
#include <QFile>
#include <QFileInfo>
#include <QQueue>

class HttpClient : public QObject
{
    Q_OBJECT
public:
    explicit HttpClient(QObject *parent = nullptr);
    explicit HttpClient(const QString &baseUrl,QObject *parent = nullptr);
    explicit HttpClient(const QString &baseUrl,const QString &token,QObject *parent = nullptr);
    ~HttpClient();
    QNetworkReply* post(const QString &url, const QByteArray &data=nullptr);
    QNetworkReply* post(const QUrl &url,QHttpMultiPart *multiPart);
    QNetworkReply* get(const QString &url);

    QNetworkReply* sendTextMsg(const QByteArray &data);
    QNetworkReply* upLoadFile(const QString &url,const QString &path,const QString &uuid);
    QNetworkReply* downLoadFile(const QString &url, const QByteArray &data=nullptr);

    void setBaseUrl(const QString& url);
    void setToken(const QString& token);

signals:
    void finished(const QUrl &url, const QByteArray &data);
    void errorOccurred(const QUrl &url, const QNetworkReply::NetworkError &error);

private slots:
    void onReplyFinished(QNetworkReply *reply);

private:
    QNetworkAccessManager *manager=nullptr;

    QString baseUrl;//用于统一设置请求的地址
    QByteArray token;//用于设置请求时携带token


    QNetworkReply* post(const QNetworkRequest &request,const QByteArray &data);
    QNetworkReply* postJson(const QUrl &url,const QByteArray &data);
    QNetworkReply* postFile(const QUrl &url,const QByteArray &data);

    QNetworkReply* get(const QNetworkRequest &request);
    QNetworkReply* getJson(const QUrl &url);
    QNetworkReply* getFile(const QUrl &url);

    void cancelRequest(const QUrl &url);
    QString handleUrl(const QString &url);

    void printDetail(const QUrl &url,const QByteArray &responseData);
    void printError(const QUrl &url,const QString &errorString);

};

#endif // HTTPCLIENT_H
